<?php
class DistrictModel extends BaseModel {
	/**
	 * 日志对象
	 *
	 * @var Logger
	 */
	private $_logger;
	
	/**
	 *
	 * @var array
	 */
	private $_map = array ();
	
	/**
	 * <h2>构造函数，构造父类，初始化日志对象</h2>
	 */
	public function __construct() {
		parent::__construct ();
		Logger::configure ( ROOT_PATH . 'config/log_config.xml' );
		$this->_logger = Logger::getLogger ( __CLASS__ );
	}
	
	/**
	 * <h2>获取所有的区县</h2>
	 *
	 * @return CLIST(CMAP(id,name,cid))
	 */
	public function getAll() {
		$list = new CLIST ();
		$conn = DBHelper::getDB ( false );
		$query = "SELECT id, name, cid FROM districts";
		$resultSet = $conn->select ( $query );
		for($i = 0; $i < count ( $resultSet ); ++ $i) {
			$map = new CMAP ( $resultSet [$i] );
			$list->append ( $map );
		}
		return $list;
	}
	
	/**
	 * <h2>获取所属城市的ID</h2>
	 *
	 * @param CINT $distId        	
	 * @return CINT
	 */
	public function getCityId(CINT $distId) {
		if ($distId == null || $distId->getValue () <= 0) {
			return null;
		}
		$query = "SELECT cid FROM districts WHERE id=:id";
		$param = array (
				"id" => $distId->getValue () 
		);
		$map [] = array (
				"id",
				"int" 
		);
		try {
			$resultSet = $this->_conn->select ( $query, $param, $map );
			if (count ( $resultSet ) > 0) {
				return $resultSet [0] ['cid'];
			}
		} catch ( Exception $e ) {
			$this->_logger->error ( 'Get city id failed in ' . __CLASS__ );
			return null;
		}
		return null;
	}
	
	/**
	 * <h2>根据城市ID获取该城市对应的所有区县</h2>
	 *
	 * @param CINT $cid        	
	 * @return CLIST(CMAP(id,name))
	 */
	public function getDistrictByCityId(CINT $cid) {
		$dlst = new CLIST ();
		$query = 'SELECT id, name FROM districts WHERE cid=:cid';
		$param ['cid'] = $cid->getValue ();
		$map [] = array (
				'cid',
				'int' 
		);
		$resultSet = $this->_conn->select ( $query, $param, $map );
		for($i = 0; $i < count ( $resultSet ); ++ $i) {
			$map = new CMAP ( $resultSet [$i] );
			$dlst->append ( $map );
		}
		return $dlst;
	}
}